/**
 * Licensed under the Apache License Version 2.0.
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */
package net.interknit.knitter.fw.hook;

import java.util.HashMap;
import java.util.Map;

import net.interknit.knitter.fw.AccessController;

import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.jaxrs.JAXRSServiceImpl;
import org.apache.cxf.message.Message;
import org.apache.cxf.service.Service;

public class AuthenticationHook extends ReceiveHook
{
	@Override
	public void handleMessage(Message message) throws Fault
	{
		super.handleMessage(message);

		try
		{
//			System.out.println("#### ENDPOINT_ADDRESS: " + message.get(Message.ENDPOINT_ADDRESS));
//			System.out.println("#### PATH_INFO: " + message.get(Message.PATH_INFO));
//			System.out.println("#### BASE_PATH: " + message.get(Message.BASE_PATH));
//			System.out.println("#### MAINTAIN_SESSION: " + message.get(Message.MAINTAIN_SESSION));
//			System.out.println("#### QUERY_STRING: " + message.get(Message.QUERY_STRING));
//			System.out.println("#### REQUEST_URI: " + message.get(Message.REQUEST_URI));
//
			Service service = message.getExchange().getService();

			Map<String, Object> map = new HashMap<String, Object>();

			for(String key : service.keySet())
				map.put(key, service.get(key));

			AccessController ac = AccessController.getInstance();

			ac.setServiceName(service.getName());
			ac.setServiceAttributes(map);

			if(service instanceof JAXRSServiceImpl)
			{
				JAXRSServiceImpl impl = (JAXRSServiceImpl) service;

				ac.setBeanName(impl.getBeanName());
			}

			AccessController.getInstance().allow(
					getSecurityContext(message), getRequest(message));
		}
		catch(NullPointerException npe)
		{
			throw new Fault(npe);
		}
	}
}
